package bingo.codeweaver.core.template;

import java.io.StringWriter;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

/**
 * Mar 9, 2009 4:49:07 AM VelocityTemplateEngine.java
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:
 * ChangeLog:
 */
public class VelocityTemplateEngine implements TemplateEngine {
	
	
	public VelocityTemplateEngine() {
		initVelocity();
	}
	/**
	 * 初始化模板引擎
	 */
	private void initVelocity() {
//		Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
		try {
			Velocity.init();
		} catch (Exception e) {
			throw new RuntimeException("初始化Velocity引擎失败", e);
		}
	}

	public String evaluate(String templateName,String template, Map<String, Object> context) throws Exception {
		VelocityContext vc = new VelocityContext();
		for(String key : context.keySet()){
			vc.put(key, context.get(key));
		}
		StringWriter sw = new StringWriter();
		Velocity.evaluate(vc, sw, templateName, template);
		return sw.toString();
	}

	/* (non-Javadoc)
	 * @see bingo.codeweaver.core.template.TemplateEngine#merge(bingo.codeweaver.core.template.TemplateMetadata, java.util.Map)
	 */
	public String merge(TemplateMetadata template, Map<String, Object> context) throws  Exception {
		VelocityContext vc = new VelocityContext();
		for(String key : context.keySet()){
			vc.put(key, context.get(key));
		}
		Template vt = Velocity.getTemplate(template.getPath(), template.getEncoding());
		StringWriter sw = new StringWriter();
		vt.merge(vc, sw);
		return sw.toString();
	}

}
